package UIFree.abox
{
	import UIFree.controls.base.uif_previewSource;
	import UIFree.controls.base.uif_source;
	import UIFree.uif_component;
	
	import UIUtils.uif_util;
	import UIUtils.uif_utilR;
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	
	public class uif_imageSource extends uif_previewSource {
		public static const PREVLAYERSTYLENAME: String = 'previewLayer';
		private static var _previewLayer: uif_source;
		public static var SHOWALPHA: Number = 0.8;
		
		public function uif_imageSource(parent:uif_component, ax:int=0, ay:int=0, awidth:int=0, aheight:int=0, styleClass:String='') {
			super(parent, ax, ay, awidth, aheight, styleClass);
		}
		
		override protected function doLoad(e: Event): void {
			super.doLoad(e);
			if (sourceScale < 1) mouseListenEvent();
			if (_previewLayer) updatePosition();
		}
		
		protected function mouseListenEvent(): void {
			addEvent(MouseEvent.ROLL_OVER, onFocus, mouseDispatcher);
			addEvent(MouseEvent.ROLL_OUT, onUnFocus, mouseDispatcher);
		}
		
		protected function get mouseDispatcher(): EventDispatcher {
			return parent;
		}
		
		protected function onFocus(e: MouseEvent): void {
			focus = true;
		}
				
		protected function onUnFocus(e: MouseEvent): void {
			focus = false;
		}
		
		protected function get focus(): Boolean {
			return _previewLayer && (_previewLayer.source.sourceUrl == source.sourceUrl);
		}
		
		protected function previewLayer(): uif_source {
			return _previewLayer;
		}
		
		protected function updatePosition(): void {
			_previewLayer.position = uif_util.inBox(app.mousePos, 
				new Point(_previewLayer.source.width, _previewLayer.source.height),
				app.getInner());
		}
		
		protected function set focus(a_set: Boolean): void {
			if (a_set) {
				var space: Number = app.getStyleSpace(PREVLAYERSTYLENAME, true) * 2;
				
				if (!_previewLayer) {
					_previewLayer = new uif_source(app, 0, 0, imageSize.x + space, imageSize.y + space, PREVLAYERSTYLENAME);
					_previewLayer.setVisibility(false);
					_previewLayer.addEvent(MouseEvent.MOUSE_MOVE, function(e: MouseEvent): void {
						updatePosition();
					}, app);
				}
				
				_previewLayer.resize(imageSize.x + space, imageSize.y + space);
				
				updatePosition();
				if (_previewLayer.visible) {
					_previewLayer.FXNameCancel('alpha');
					_previewLayer.alpha = SHOWALPHA;
					_previewLayer.source.loadBytes(source.contentLoaderInfo.bytes);
				} else {
					uif_utilR.waitNoOut(mouseDispatcher, function(): void {
						_previewLayer.source.loadBytes(source.contentLoaderInfo.bytes);
						_previewLayer.slideShow(null, SHOWALPHA);
					});
				}
			} else {
				if (_previewLayer) _previewLayer.slideHide();
			}
		}
	}
}